from flask import Blueprint, render_template, request, jsonify

from applications.common import curd
from applications.common.utils import validate
from applications.common.utils.http import success_api, fail_api
from applications.common.utils.rights import authorize
from applications.common.utils.validate import str_escape
from applications.extensions import db
from applications.models import CmsCategory
from applications.schemas import CmsCategorySchema

bp = Blueprint('category', __name__, url_prefix='/category')

@bp.get('/')
@authorize("cms:category:main", log=True)
def main():
    return render_template('cms/category/main.html')
    
    
@bp.post('/data')
@authorize("cms:category:main", log=True)
def data():
    data = CmsCategory.query.order_by(CmsCategory.sort).all()
    res = {
        "data": CmsCategorySchema(many=True).dump(data)
    }
    return jsonify(res)


@bp.get('/add')
@authorize("cms:category:add", log=True)
def add():
    return render_template('cms/category/add.html')


@bp.get('/tree')
@authorize("cms:category:main", log=True)
def tree():
    cate = CmsCategory.query.order_by(CmsCategory.sort).all()
    power_data = curd.model_to_dicts(schema=CmsCategorySchema, data=cate)
    power_data.append({"id": 0, "category_name": "顶级栏目", "parent_id": -1})
    res = {
        "status": {"code": 200, "message": "默认"},
        "data": power_data

    }
    return jsonify(res)


@bp.post('/save')
@authorize("cms:category:add", log=True)
def save():
    req_json = request.get_json(force=True)
    cate = CmsCategory(
        parent_id=req_json.get('parentId',0),
        category_name=str_escape(req_json.get('categoryName')),
        sort=str_escape(req_json.get('sort')),
        category_url=str_escape(req_json.get('categoryUrl')),
        status=str_escape(req_json.get('status')),
        remark=str_escape(req_json.get('remark'))
    )
    r = db.session.add(cate)
    db.session.commit()
    return success_api(msg="成功")


@bp.get('/edit')
@authorize("cms:category:edit", log=True)
def edit():
    _id = request.args.get("categoryId")
    cate = curd.get_one_by_id(model=CmsCategory, id=_id)
    return render_template('cms/category/edit.html', cate=cate)


# 启用
@bp.put('/enable')
@authorize("cms:category:edit", log=True)
def enable():
    id = request.get_json(force=True).get('categoryId')
    if id:
        enable = 1
        d = CmsCategory.query.filter_by(id=id).update({"status": enable})
        if d:
            db.session.commit()
            return success_api(msg="启用成功")
        return fail_api(msg="出错啦")
    return fail_api(msg="数据错误")


# 禁用
@bp.put('/disable')
@authorize("cms:category:edit", log=True)
def dis_enable():
    id = request.get_json(force=True).get('categoryId')
    if id:
        enable = 0
        d = CmsCategory.query.filter_by(id=id).update({"status": enable})
        if d:
            db.session.commit()
            return success_api(msg="禁用成功")
        return fail_api(msg="出错啦")
    return fail_api(msg="数据错误")


@bp.put('/update')
@authorize("cms:category:edit", log=True)
def update():
    json = request.get_json(force=True)
    #id = json.get("deptId"),
    id = str_escape(json.get("categoryId"))
    data = {
		"parent_id": validate.str_escape(json.get("parentId")),
        "category_name": validate.str_escape(json.get("categoryName")),
        "sort": validate.str_escape(json.get("sort")),
        "category_url": validate.str_escape(json.get("categoryUrl")),
        "status": validate.str_escape(json.get("status")),
        "remark": validate.str_escape(json.get("remark"))
    }
    d = CmsCategory.query.filter_by(id=id).update(data)
    if not d:
        return fail_api(msg="更新失败")
    db.session.commit()
    return success_api(msg="更新成功")


@bp.delete('/remove/<int:_id>')
@authorize("cms:category:remove", log=True)
def remove(_id):
    d = Dept.query.filter_by(id=_id).delete()
    if not d:
        return fail_api(msg="删除失败")
    res = User.query.filter_by(dept_id=_id).update({"dept_id": None})
    db.session.commit()
    if res:
        return success_api(msg="删除成功")
    else:
        return fail_api(msg="删除失败")
